#! /usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter as tk
import os
import sys
import threading

from UI import pyinstallerUI


class MainPyinstaller(pyinstallerUI.PyinstallerUI):
    def __init__(self, master=None):
        super(MainPyinstaller, self).__init__()
        self.start_flag = False

    def Generate(self):
        '''
        生成可执行文件
        '''
        if not self.start_flag:
            thread_generate = threading.Thread(target=self.ThreadGenerate)
            thread_generate.setDaemon(True)
            thread_generate.start()
        else:
            self.frm_status_label["text"] = "Being Packing, please re-run later!"

    def ThreadGenerate(self):
        '''
        线程执行生成动作
        '''
        if len(self.entry_value_list[0].get()) == 0:
            self.frm_status_label["text"] = "Please select the source file!"
            return
        try:
            self.start_flag = True
            command = self.assembly_command_string()
            self.frm_status_label["text"] = "Being Packing, please wait a moment!"
            os.system(command)
            self.start_flag = False
            self.frm_status_label["text"] = "Complete package!"
        except Exception as e:
            self.frm_status_label["text"] = e.message
            self.start_flag = False

    def assembly_command_string(self):
        '''
        组装终端执行命令行
        '''
        self.command_string = ""
        self.command_list = list()

        self.command_list.append("pyinstaller")

        if len(self.entry_value_list[1].get()) > 0:
            self.command_list.append("--workpath=" + self.entry_value_list[1].get())

        if len(self.entry_value_list[2].get()) > 0:
            self.command_list.append("--distpath=" + self.entry_value_list[2].get())

        if len(self.entry_value_list[3].get()) > 0:
            self.command_list.append("--icon=" + self.entry_value_list[3].get())

        if self.onefile.get() == 1:
            self.command_list.append("--onefile")

        if self.noconsole.get() == 1:
            self.command_list.append("--noconsole")
            
        if self.rename_exe.get() == 1:
            if len(self.rename_strvar.get()) > 0:
                self.command_list.append("--name=" + self.rename_strvar.get())

        if len(self.entry_value_list[0].get()) > 0:
            self.command_list.append(self.entry_value_list[0].get())

        self.command_string = " ".join(self.command_list)
        return self.command_string

if __name__ == '__main__':
    '''
    main loop
    '''
    root = tk.Tk()
    root.title("Pyinstaller Tool")
    MainPyinstaller(master=root)
    root.resizable(False, False)
    root.mainloop()